//
//  TodaySleepCellViewModel.swift
//  MoyoungHome
//
//  Created by 易先生 on 2022/7/27.
//

import UIKit
import RxCocoa
import MYModule

open class HomeSleepViewModel: HomeBaseViewModel {
    

    public let UIRelay: BehaviorRelay<HomeSleepModel>

    public init(date: Date) {
        
        let model = HomeSleepModel()
        UIRelay = BehaviorRelay<HomeSleepModel>(value: model)
        
        super.init(cellType: .sleep)
        
        reloadData(date)
        
    }
    
    public override func reloadData(_ date: Date? = nil) {
        
        guard let date = date else {
            return
        }

        let model = self.UIRelay.value
        
        let userModel = UserCacheManagement.userInfo()
        let goal = userModel.getSleepGoal()
        model.targetHour = goal
        
        guard let sleepModel = SleepModel.day(date: date) else {
            
            let model = HomeSleepModel()
            model.targetHour = goal
          
            UIRelay.accept(model)
            return
        }
        
        let dateStr = Self.dateStr(date: sleepModel.date)
        model.date = dateStr
        
        let total = sleepModel.total
        
        if total > 0 {
        
            model.hour = total/60
            model.minute = total%60
           
        }
        
        if let startTimeString = sleepModel.fallAsleepDate?.toString(.custom("MM/dd HH:mm")){
          
            model.fallAsleep = startTimeString
        }
        if let endTimeString = sleepModel.awakeDate?.toString(.custom("MM/dd HH:mm")){
            model.wakeUp = endTimeString
        }
        
        let lineDataLists = sleepModel.detail.map { detail -> SegmentLineChartModel in
            
            // 快速眼动 绘制在第二行，而 detail.type = 3,所以
            // 手动调整位置
            
            var type = detail.type
             if detail.type == 1 {
                type = 2
            } else if detail.type == 2 {
                type = 3
            } else if detail.type == 3 {
                type = 1
            }
            
            return SegmentLineChartModel(total: Double(detail.total), type: type)
        }
        model.lineData = lineDataLists
        
        model.hasData = sleepModel.total != 0
        
        UIRelay.accept(model)
        
    }
    
 
    
   
    
}
